package com.gwl.server.controller;


import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gwl.server.dto.PassDto;
import com.gwl.server.entity.SysRole;
import com.gwl.server.entity.SysUser;
import com.gwl.server.entity.SysUserRole;
import com.gwl.server.lang.Const;
import com.gwl.server.lang.Result;
import net.sf.jsqlparser.expression.operators.arithmetic.Concat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author gwl
 * @since 2022-05-02
 */
@RestController
@RequestMapping("/sys/user")
public class SysUserController extends BaseController {

    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;

    @PreAuthorize("hasAnyAuthority('sys:user:list')")
    @GetMapping("/info/{id}")
    public Result info(@PathVariable("id") Long id){
        SysUser sysUser = sysUserService.getById(id);
        Assert.notNull(sysUser, "找不到该管理员");

        List<SysRole> sysRoles = sysRoleService.listRolesByUserId(id);
        sysUser.setSysRoles(sysRoles);

        return Result.succ(sysUser);
    }

    @GetMapping("/list")
    @PreAuthorize("hasAnyAuthority('sys:user:list')")
    public Result list(String username){
        Page<SysUser> pageData = sysUserService.page(getPage(), new QueryWrapper<SysUser>().like(StrUtil.isNotBlank(username), "username", username));
        pageData.getRecords().forEach(u -> {
            u.setSysRoles(sysRoleService.listRolesByUserId(u.getId()));
        });
        return Result.succ(pageData);
    }

    @PreAuthorize("hasAnyAuthority('sys:user:save')")
    @PostMapping("/save")
    public Result save(@Validated @RequestBody SysUser sysUser){
        sysUser.setCreated(LocalDateTime.now());
        sysUser.setStatu(Const.STATUS_OFF);

        //默认头像
        sysUser.setAvatar(Const.DEFULT_AVATAR);

        // 默认密码
        String password = bCryptPasswordEncoder.encode(Const.DEFFULT_PASSWORD);

        sysUserService.save(sysUser);

        return Result.succ(sysUser);
    }

    @PreAuthorize("hasAnyAuthority('sys:user:update')")
    @PostMapping("/update")
    public Result update(@Validated @RequestBody SysUser sysUser){
        sysUser.setCreated(LocalDateTime.now());
        sysUserService.updateById(sysUser);
        return Result.succ(sysUser);
    }

    @Transactional
    @PreAuthorize("hasAnyAuthority('sys:user:delete')")
    @PostMapping("/delete")
    public Result delete(@RequestBody Long[] ids){
        sysUserService.removeByIds(Arrays.asList(ids));
        sysUserRoleService.remove(new QueryWrapper<SysUserRole>().in("user_id", ids));
        return Result.succ("");
    }

    @PreAuthorize("hasAnyAuthority('sys:user:role')")
    @Transactional
    @PostMapping("/role/{userId}")
    public Result rolePerm(@PathVariable("userId") Long userId, @RequestBody Long[] roleIds){
        ArrayList<SysUserRole> sysUserRoles = new ArrayList<>();
        Arrays.stream(roleIds).forEach(r ->{
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setRoleId(r);
            sysUserRole.setUserId(userId);
            sysUserRoles.add(sysUserRole);
        });
        sysUserRoleService.remove(new QueryWrapper<SysUserRole>().eq("user_id", userId));
        sysUserRoleService.saveBatch(sysUserRoles);
        // 删除缓存
        SysUser byId = sysUserService.getById(userId);
        sysUserService.clearUserAuthorityInfo(byId.getUsername());
        return Result.succ("");
    }

    @PreAuthorize("hasAnyAuthority('sys:user:repass')")
    @PostMapping("/repass")
    public Result repass(@RequestBody Long userId){
        SysUser sysUser = sysUserService.getById(userId);
        sysUser.setPassword(bCryptPasswordEncoder.encode(Const.DEFFULT_PASSWORD));
        sysUser.setUpdated(LocalDateTime.now());
        sysUserService.updateById(sysUser);

        return Result.succ("");
    }

    @Transactional
    @PostMapping("/updatePass")
    public Result repass(@Validated @RequestBody PassDto passDto, Principal principal){

        SysUser sysUser = sysUserService.getByUserName(principal.getName());

        boolean matches = bCryptPasswordEncoder.matches(passDto.getCurrentPass(), sysUser.getPassword());
        if(!matches){
            return Result.fail("旧密码不正确");
        }
        sysUser.setPassword(bCryptPasswordEncoder.encode(passDto.getPassword()));
        sysUser.setUpdated(LocalDateTime.now());
        sysUserService.updateById(sysUser);

        return Result.succ("");
    }

}
